package com.starblink.imgsearch.findsimilar.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.base.fragment.BaseTVMLazyLoadingFragment
import com.starblink.android.basic.data.model.product.ProductFWrap
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.imgsearch.databinding.*
import com.starblink.imgsearch.findsimilar.ext.setData
import com.starblink.imgsearch.findsimilar.ui.cell.EmptyBodyCell
import com.starblink.imgsearch.findsimilar.ui.cell.LoadingHeadCell
import com.starblink.imgsearch.findsimilar.ui.view.SimilarHeaderCollapseDecorator
import com.starblink.imgsearch.result.ui.cell.ResultTipCell
import com.starblink.library.widget.loading.GoodsCardLoadingCell
import com.starblink.library.widget.product.ProductCardScene
import com.starblink.library.widget.product.SimpleProductCardCell
import com.starblink.rocketreserver.fragment.ProductF

internal class SimilarTabFragment :
    BaseTVMLazyLoadingFragment<FragmentSimilarResultBinding, SimilarTabViewModel>() {

    companion object {
        fun newInstance(
            position: Int,
            region: String,
            picUrl: String,
            productId: String,
            type: Int,
            list: List<ProductFWrap?>? = null,
            mainProduct: ProductF? = null,
        ) = SimilarTabFragment().apply {
            arguments = Bundle().apply {
                putInt("position", position)
            }
            this.list = list
            this.picUrl = picUrl
            this.region = region
            this.productId = productId
            this.type = type
            this.mainProduct = mainProduct
        }

        private const val TAG = "ResultTabFragment"
    }

    private var list: List<ProductFWrap?>? = null

    var picUrl = ""

    var region = ""

    var productId: String = ""

    var type = 1

    var mainProduct: ProductF? = null

    var bottomSheetExpand = false

    private val tabPosition by lazyOnNone {
        arguments?.getInt("position") ?: 0
    }

    private var scrollY = 0

    private lateinit var mainPrdBinding: LayoutFindSimilarItemBinding


    private val adapter by lazyOnNone {
        MutableAdapter(viewModel.adapterList).apply {
            addVhDelegate {
                SimpleProductCardCell(
                    viewBinding.refresher,
                    viewBinding.recycler,
                    it,
                    ProductCardScene.FIND_SIMILAR,
                    pageTrackTag = this@SimilarTabFragment.hashCode().toString(),
                )
            }
            addVhDelegate {
                ResultTipCell(CellResultTipBinding.inflate(layoutInflater).apply {
                    root.enableCorner(32.dp2px(), "top")
                })
            }
            addVhDelegate {
                EmptyBodyCell(CellSimilarEmptyBodyBinding.inflate(layoutInflater))
            }
            addVhDelegate {
                LoadingHeadCell(it)
            }
            addVhDelegate {
                GoodsCardLoadingCell(it)
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }


    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentSimilarResultBinding = FragmentSimilarResultBinding.inflate(inflater)

    override fun startObserve() {
        viewModel.resultLD.observe(this) { it ->
            if (viewModel.pageNo == 1) {
                if (it.isEmpty()) {
                    showEmpty()
                } else {
                    viewModel.adapterList.run {
                        add(0, viewModel.tipItem.apply {
                            visible = true
                            firstScore = it.firstOrNull()?.productF?.score ?: 0.0
                        })
                        addAll(it)
                        adapter.refreshAll()
                    }
                    showContent()
                }
            } else {
                showContent()
                val seeIndex = viewModel.adapterList.size
                viewModel.adapterList.addAll(it)
                adapter.notifyItemRangeChanged(seeIndex, it.size)
            }
            if (it.isEmpty()) {
                viewBinding.refresher.finishLoadMoreWithNoMoreData()
            }
        }
        viewModel.loadStateLD.observe(this) { it ->
            if (it == SimilarTabViewModel.LOAD_STATE_FINISH) {
                viewBinding.refresher.finishLoadMore()
            }
        }
        viewModel.mainPrdLD.observe(this) {
            mainPrdBinding.setData(it, picUrl)
            viewBinding.recycler.postInvalidateDelayed(100L)
        }
    }

    override fun initData() {
        viewModel.productId = productId
        viewModel.picUrl = picUrl
        viewModel.regin = region
        viewModel.type = type
        list?.let {
            viewModel.products.addAll(it.filterNotNull())
        }
        viewModel.initAdapterList()
        adapter.refreshAll()
    }

    private fun initView() {
        showStateSuccess()

        mainPrdBinding =
            LayoutFindSimilarItemBinding.inflate(layoutInflater, viewBinding.root, false)
        mainPrdBinding.setData(mainProduct, picUrl)
        SimilarHeaderCollapseDecorator.attach(viewBinding.recycler, mainPrdBinding.root)
        mainPrdBinding.root.alpha = 0f //
        viewBinding.root.addView(
            mainPrdBinding.root,
            ViewGroup.MarginLayoutParams(
                ViewGroup.MarginLayoutParams.MATCH_PARENT,
                ViewGroup.MarginLayoutParams.WRAP_CONTENT
            ).apply {
                leftMargin = 12.dp2px()
                rightMargin = 12.dp2px()
            })
        viewBinding.recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                scrollY += dy
                mainPrdBinding.root.translationY = -scrollY.toFloat()
            }
        })
        viewBinding.recycler.enableCorner(32.dp2px(), "top")
        viewBinding.recycler.bindProductFeeds(adapter)
        //viewBinding.recycler.bindFeedsNoviceHelper(requireActivity())
        viewBinding.refresher.run {
            setEnableAutoLoadMore(true)
            setEnableLoadMoreWhenContentNotFull(false) // 重要，不满一屏时上拉加载更多会导致手势冲突
            setEnableNestedScroll(false)
            setEnableRefresh(false)
            setEnableLoadMore(false)
            setOnLoadMoreListener {
                //viewModel.loadMoreRecData()
                viewModel.loadMoreContent()
            }
        }
    }

    override fun onLazyInitData() {
        if (viewModel.products.isNotEmpty()) {
            /*viewModel.pageNo++
            viewModel.loadInitData()*/
            showContent()
        } else {
            if (tabPosition == 0) {
                showEmpty()
            } else {
                showLoading()
                viewModel.loadInitData()
            }
        }
    }

    private fun showContent() {
        viewModel.adapterList.clear()
        viewModel.initAdapterList()
        adapter.refreshAll()
    }

    private fun showLoading() {
        viewModel.adapterList.run {
            clear()
            addAll(viewModel.loadingData)
        }
        adapter.refreshAll()
    }

    private fun showEmpty() {
        viewModel.adapterList.run {
            clear()
            add(viewModel.loadingModel)
            add(viewModel.emptyBodyModel)
        }
        adapter.refreshAll()
    }

    fun reload() {
        view ?: return
        viewModel.picUrl = picUrl
        viewModel.regin = region
        viewModel.type = type
        viewModel.resetData()
        viewModel.loadInitData()
        viewBinding.refresher.setNoMoreData(false)
        mainPrdBinding.setData(null, null)
        showLoading()
    }

    override fun initView(view: View) {

    }

    override fun initLoad() {

    }

    override fun onResume() {
        super.onResume()
        pageExposure(SpmPageDef.FIND_SIMILAR_PAGE)
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(SpmPageDef.FIND_SIMILAR_PAGE)
    }


}